#include "ClinetConnect.h"
#include "UdpConnect.h"
#include "BaseMsg.h"
#include <unistd.h>
#include <iostream>

ClientConnect::ClientConnect()
{
}
ClientConnect::~ClientConnect()
{
    Close();
}

int ClientConnect::Connect(std::string ip,int port)
{
    udp = std::make_shared<UdpConnect>(ip,port);
    udp->init();
    uint32_t sessid = 111;          //TODO：等下改成服务器发来的
    conn = std::make_shared<KcpConnect>(udp,sessid);
    conn->Connect();
    t1 = std::thread(ClientConnect::MainFun,this);
    return 0;
}


void ClientConnect::MainFun( ClientConnect *ptr )
{
    while(1)
    {
        ptr->Update();
        char buf[1024];
        struct sockaddr_in client;
        int len = ptr->udp->recv(buf,1024,client);
        if(len < 8) 
            continue;
        ptr->Logic(buf,len,client);
        usleep(10);
    }
}

void  ClientConnect::Update()
{
    conn->Update();
}
void ClientConnect::Logic( char *buf, int len,struct sockaddr_in addrs )
{
    uint32_t code = (uint32_t)UdpConnect::bytesToInt(buf);
    uint32_t id = (uint32_t)UdpConnect::bytesToInt(buf+4);
    switch(code)
    {
        case BaseMsg::MSG_HEAD_TEPE_CONTENT:
            {
                if((uint32_t)id != conn->GetSeeeid())
                {
                    std::cout<<"error id="<<id <<std::endl;
                    return;
                }
                udp->put(buf+8,len-8);
            }
            break;
        case BaseMsg::MSG_HEAD_TEPE_CONNECT_ACK:
            {
                conn->UpdateSessid(id);
            }
            break;
        case BaseMsg::MSG_HEAD_TEPE_CONNECT_FAIL:
            {
            }
            break;
        case BaseMsg::MSG_HEAD_TEPE_CONNECT_EXIST:
            {
            }
            break;
        case BaseMsg::MSG_HEAD_TEPE_CLOSE_NO_EXIST:
            {
            }
            break;
        case BaseMsg::MSG_HEAD_TEPE_CLOSE_ACK:
            {
            }
            break;
        default:
            break;
    }
}
void ClientConnect::Send( char *buf, int len )
{
    conn->Send(buf,len);
}
int ClientConnect::Recv( char *buf, int len )
{
    return conn->Recv(buf,len);
}
int ClientConnect::Close()
{
    conn->Close();
    return 0;
}

